package alexattar.gdxtest.services;

import alexattar.gdxtest.GdxTestGame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Disposable;

public class MusicManager implements Disposable{

	public enum TyrianMusic {
		MENU("music/menu.ogg"),
		LEVEL("music/level.ogg");
		
		private final String filename;
		
		private TyrianMusic (String filename) {
			this.filename = filename;
		}
		
		public String getFilename() {
			return filename;
		}
	}
	
	private Music musicBeingPlayed;
	private float volume = 1f;
	private boolean enabled = true;
	
	
	public MusicManager() {
	}
	
	public void play(TyrianMusic music) {
		if (!enabled) return;
		
		Gdx.app.log(GdxTestGame.LOG, "Playing music: " + music.name());
		stop();
		
		FileHandle musicFile = Gdx.files.internal(music.getFilename());
		musicBeingPlayed = Gdx.audio.newMusic(musicFile);
		musicBeingPlayed.setVolume(volume);
		musicBeingPlayed.setLooping(true);
		musicBeingPlayed.play();
	}
	
	public void stop() {
		if (musicBeingPlayed != null) {
			Gdx.app.log(GdxTestGame.LOG, "Stopping current music" );
			musicBeingPlayed.stop();
			musicBeingPlayed.dispose();
		}
	}
	
	public void setVolume(float volume) {
		Gdx.app.log(GdxTestGame.LOG, "Adjusting music volume to: " + volume);
		if (volume < 0 || volume > 1f) {
			throw new IllegalArgumentException("The colume must be inside the range: [0,1]");
		}
		this.volume = volume;
		
		if (musicBeingPlayed != null) {
			musicBeingPlayed.setVolume(volume);
		}
	}
	
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
		if (!enabled) {
			stop();
		}
	}
	
	@Override
	public void dispose() {
		Gdx.app.log(GdxTestGame.LOG, "Disposing music managed");
		stop();
	}

}
